package com.fanshuai.queue;

public class ArrayQueue<E> implements Queue<E> {
    private E[] array;
    private int head;
    private int tail;

    private int capacity;

    public ArrayQueue(int capacity) {
        this.capacity = capacity + 1;
        array = (E[]) new Object[capacity + 1];

        this.head = 0;
        this.tail = 0;
    }

    @Override
    public int size() {
        if (tail >= head) {
            return tail - head;
        } else {
            int empty = head - tail;
            return capacity - empty;
        }
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return (tail + 1) % capacity == head;
    }

    @Override
    public void enqueue(E data) {
        if (isFull()) {
            throw new IndexOutOfBoundsException("queue full");
        }

        array[tail] = data;
        tail = (tail + 1) % capacity;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("queue empty");
        }

        E e = array[head];
        array[head] = null;
        head = (head + 1) % capacity;
        return e;
    }

    @Override
    public E peek() {
        return array[head];
    }
}
